﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System.Diagnostics.CodeAnalysis;
using TrackSystem.Entities.Dtos.Sensor;
using TrackSystem.UI.Server.HttpRepository.Channel;
using TrackSystem.UI.Server.HttpRepository.Equip;
using TrackSystem.UI.Server.HttpRepository.Sensor;

namespace TrackSystem.UI.Server.Pages.Configuration
{
    public partial class SensorsTable
    {
        [Inject]
        [NotNull]
        private IStringLocalizer<SensorWithChannelDto>? Localizer { get; set; }

        [NotNull]
        [Inject]
        public ISensorHttpRepository repo { get; set; }

        [Inject]
        [NotNull]
        public IChannelHttpRepository chnRepo { get; set; }

        [Inject]
        [NotNull]
        public IEquiplHttpRepository eqpRepo { get; set; }


        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

       /// <summary>
        /// 获得/设置 分页配置数据源
        /// </summary>
        private static IEnumerable<int> PageItemsSource => new int[] { 10, 20, 40 };

        private  List<SelectedItem> lstStation;
        private List<SelectedItem> lstEquip;

        protected override async Task OnInitializedAsync()
        {
            if (chnRepo == null)
            {
                throw new InvalidOperationException("Repository is not initialized.");
            }
            // 初始化数据
            var items = await chnRepo.GetAll();
            lstStation = [.. items.Select(c => new SelectedItem(c.Id.ToString(), $"{c.Name}/{c.Protocol}"))];

            var equips = await eqpRepo.GetAll();
            lstEquip = equips.Select(c=>new SelectedItem(c.Id.ToString(),c.Name)).ToList();
        }



        private async Task<QueryData<SensorWithChannelDto>> OnQueryAsync(QueryPageOptions options)
        {
            try
            {
                if (repo == null)
                {
                    await ToastService.Error("通道列表", "数据库未初始化");
                    return new QueryData<SensorWithChannelDto>();
                }

                var items = await repo.GetAll();

                items = items.Where(options.ToFilterFunc<SensorWithChannelDto>());

                // 排序
                var isSorted = false;
                if (!string.IsNullOrEmpty(options.SortName))
                {
                    items = items.Sort(options.SortName, options.SortOrder);
                    isSorted = true;
                }

                var total = items.Count();
                var result = new QueryData<SensorWithChannelDto>()
                {
                    Items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(),
                    TotalCount = total,
                    IsFiltered = true,
                    IsSorted = isSorted,
                    IsSearch = true
                };

                return await Task.FromResult(result);
            }
            catch (Exception)
            {
                return new QueryData<SensorWithChannelDto>
                {
                    Items = new List<SensorWithChannelDto>(),
                    TotalCount = 0,
                    IsFiltered = false,
                    IsSorted = false,
                    IsSearch = false
                };
            }
        }

        private async Task<bool> OnSaveAsync(SensorWithChannelDto snr, ItemChangedType changedType)
        {
            switch (changedType)
            {
                case ItemChangedType.Add:
                {
                    var result = await repo.InsertAsync(snr);
                    if (!result.Success)
                    {
                        await ToastService.Error("传感器列表", result.Message);
                    }
                    return result.Success;
                }
                case ItemChangedType.Update:
                {
                    var result = await repo.UpdateAsync(snr);
                    if (!result.Success)
                    {
                        await ToastService.Error("传感器列表", result.Message);
                    }
                    return result.Success;
                }
                default:
                    return true;
            }
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<SensorWithChannelDto> snrs)
        {
            bool ret = true;
            foreach(var item in snrs)
            {
                var result = await repo.DeleteAsync(item.Id);
                if (result.Success)
                {
                    continue;
                }

                await ToastService.Error("传感器列表", result.Message);
                ret = false;
            }

            return ret;
        }
    }
}
